import re
import pandas as pd
import argparse
from openpyxl import load_workbook
from datetime import datetime
import os

# 定义正则表达式来匹配需要的数据块
pattern = re.compile(r"antiuav410_test\s+\|\s+AUC\s+\|\s+OP50\s+\|\s+OP75\s+\|\s+Precision\s+\|\s+Norm Precision\s+\|\s*\n(ostrack_antiuav410_test_\d+\s+\|\s+[\d.]+\s+\|\s+[\d.]+\s+\|\s+[\d.]+\s+\|\s+[\d.]+\s+\|\s+[\d.]+\s+\|)")

def parse_log_file(log_file_path, config_value): 
    # 设置输出路径
    output_dir = os.path.join(os.getcwd(), 'log2excel')
    os.makedirs(output_dir, exist_ok=True)
    output_excel_path = os.path.join(output_dir, f'{config_value}.xlsx')
    
    # 读取log文件
    with open(log_file_path, 'r') as file:
        log_data = file.read()

    # 匹配所有符合的内容
    matches = pattern.findall(log_data)

    # 去掉重复的匹配项
    unique_matches = list(set(matches))

    # 解析匹配到的内容
    data = []
    for match in unique_matches:
        fields = [config_value] + [field.strip() for field in match.split('|') if field.strip()]
        data.append(fields)

    # 添加日期和时间列
    current_datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    for row in data:
        row.append(current_datetime)

    # 创建DataFrame
    columns = ["Config", "Tracker", "AUC", "OP50", "OP75", "Precision", "Norm Precision", "DateTime"]
    df = pd.DataFrame(data, columns=columns)

    # 数据处理步骤
    df["AUC"] = df["AUC"].astype(float)
    df["OP50"] = df["OP50"].astype(float)
    df["OP75"] = df["OP75"].astype(float)
    df["Precision"] = df["Precision"].astype(float)
    df["Norm Precision"] = df["Norm Precision"].astype(float)

    # # 对Tracker列用下划线进行切分，并按照切分后的最后一项进行排序
    # df["Tracker_Split_Last"] = df["Tracker"].apply(lambda x: int(x.split('_')[-1]))
    # df.sort_values(by="Tracker_Split_Last", ascending=True, inplace=True)
    # df.drop(columns=["Tracker_Split_Last"], inplace=True)
    

    # 对Tracker列用下划线进行切分，并按照切分后的最后一项进行排序
    df["Tracker"] = df["Tracker"].apply(lambda x: int(x.split('_')[-1]))
    df.sort_values(by="Tracker", ascending=True, inplace=True)    
    
    # 找到AUC列数值最大的一行
    max_auc_row = df.loc[df["AUC"].idxmax()]

    # 将最大AUC行数据追加到DataFrame的最后一行
    df = pd.concat([df, max_auc_row.to_frame().T], ignore_index=True)
    
    df.to_excel(output_excel_path, index=False)

    # # 检查文件是否存在，如果存在则加载并追加内容，否则创建新文件
    # if os.path.exists(output_excel_path):
    #     book = load_workbook(output_excel_path)
    #     with pd.ExcelWriter(output_excel_path, engine='openpyxl') as writer:
    #         writer.book = book
    #         writer.sheets = {ws.title: ws for ws in book.worksheets}
    #         df_existing = pd.read_excel(output_excel_path)
    #         df_combined = pd.concat([df_existing, df], ignore_index=True)
    #         df_combined.to_excel(writer, index=False, header=True)
    # else:
    #     df.to_excel(output_excel_path, index=False)

    print("Excel file has been updated successfully.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Parse log file and convert to Excel")
    parser.add_argument("log_file", type=str, help="Path to the log file")
    parser.add_argument("config", type=str, help="Configuration value")
    
    args = parser.parse_args()
    
    parse_log_file(args.log_file, args.config)
